package com.tabbar.demo.fragment;

import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.Utils;
import com.tabbar.demo.R;
import com.tabbar.demo.bean.DayAxisValueFormatter;
import com.tabbar.demo.wiget.MyMarkerView;
import com.tabbar.demo.wiget.ProgressWithTime;
import com.tabbar.demo.wiget.SinView;
import com.tabbar.libs.view.WaveMp3Recorder;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import jaygoo.widget.wlv.WaveLineView;

/**
 * User:Shine
 * Date:2015-10-20
 * Description:
 */
public class MessageFragment extends PageFragment implements View.OnClickListener {
    private LineChart mChart;
    private int mFillColor = Color.argb(150, 51, 181, 229);
    private static final int DAYS = 6;//显示几天数据
    private SinView mSinView;
    private Button btStart;
    private Button btEnd;
    private Button bt_add_progress;
    private WaveLineView waveLineView;
    private WaveMp3Recorder mp3Recorder;
    private ImageView iv_fengjing;
    private boolean isStop = false;
    private ClipDrawable clipDrawable;
    private ProgressWithTime progressWithTime;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            clipDrawable.setLevel(clipDrawable.getLevel() + 200);
        }
    };
    private int progress = 0;

    public static PageFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        MessageFragment fragment = new MessageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = null;
        try {
            view = inflater.inflate(R.layout.fragment_message, container, false);
            initView(view);
            ArrayList<Entry> entries = initData(7, 90000);
            setDataSet(entries);
            setAnim();
            mChart.invalidate();
            requestData();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }


    private void initView(View view) {
        mChart = (LineChart) view.findViewById(R.id.linechart);
        mSinView = (SinView) view.findViewById(R.id.sin_view);
        btStart = (Button) view.findViewById(R.id.bt_start);
        progressWithTime = (ProgressWithTime) view.findViewById(R.id.progress_text);
        btEnd = (Button) view.findViewById(R.id.bt_stop);
        bt_add_progress = (Button) view.findViewById(R.id.bt_add_progress);
        iv_fengjing = (ImageView) view.findViewById(R.id.iv_fengjing);
        clipDrawable = (ClipDrawable) iv_fengjing.getDrawable();
        waveLineView = (WaveLineView) view.findViewById(R.id.waveLineView);
        mp3Recorder = (WaveMp3Recorder) view.findViewById(R.id.wave_mp3_recorder);
        btStart.setOnClickListener(this);
        btEnd.setOnClickListener(this);
        bt_add_progress.setOnClickListener(this);
        setChart();
        setXYLines();
    }

    private void setXYLines() {
        XAxis xAxis = mChart.getXAxis();
        xAxis.setEnabled(true);
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(DAYS, false);
        IAxisValueFormatter dayAxisValueFormatter = new DayAxisValueFormatter(mChart, DAYS);
//        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setValueFormatter(dayAxisValueFormatter);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        YAxis leftAxis = mChart.getAxisLeft();
//        leftAxis.setAxisMaximum(1000000);
        leftAxis.setAxisMinimum(0);
        leftAxis.setLabelCount(5, true);
        leftAxis.setDrawAxisLine(false);
        leftAxis.setDrawZeroLine(false);
        leftAxis.setDrawGridLines(true);

        mChart.getAxisRight().setEnabled(false);
    }

    private void setChart() {
        mChart.setBackgroundColor(Color.WHITE);
        mChart.setGridBackgroundColor(Color.WHITE);
        mChart.setDrawGridBackground(true);
        mChart.setDragEnabled(false);
        mChart.setScaleEnabled(false);
        mChart.setTouchEnabled(true);
        //隐藏边框
        mChart.setDrawBorders(false);
        MyMarkerView mv = new MyMarkerView(getActivity(), R.layout.custom_marker_view);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart
        // no description text
        mChart.getDescription().setEnabled(false);

        //设置单方向和双方向缩放 true x,y方向可以同时控制，false只能控制x方向的缩小放大或者Y方向的缩小放大
        mChart.setPinchZoom(false);
        Legend l = mChart.getLegend();
        l.setEnabled(false);
    }

    private ArrayList<Entry> initData(int count, float range) {
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < count; i++) {
            float val = (float) (Math.random() * range) + 50;// + (float)
            yVals1.add(new Entry(i, val));
        }
        return yVals1;
    }

    private void setDataSet(ArrayList<Entry> yVals1) {
        LineDataSet set1;
        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals1, "DataSet 1");
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            set1.setColor(getResources().getColor(R.color.color_main_blue));
            set1.setDrawCircles(false);
            set1.setLineWidth(2f);
            set1.setCircleRadius(3f);
            set1.setFillAlpha(255);
            set1.setDrawFilled(true);
            if (Utils.getSDKInt() >= 18) {
                // fill drawable only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.fade_green);
                set1.setFillDrawable(drawable);
            } else {
                set1.setFillColor(mFillColor);
            }
            set1.setHighLightColor(Color.TRANSPARENT);//设置高亮色
            set1.setDrawCircleHole(false);
            set1.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return mChart.getAxisLeft().getAxisMinimum();
                }
            });


            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            dataSets.add(set1); // add the datasets
            // create a data object with the datasets
            LineData data = new LineData(dataSets);
            data.setDrawValues(false);
            // set data
            mChart.setData(data);
        }
    }

    private void setAnim() {
        mChart.animateX(800);
    }

    /**
     * 请求数据
     */
    private void requestData() {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(12);
                if (clipDrawable.getLevel() >= 10000) {
                    timer.cancel();
                }
            }
        }, 0, 50);
    }

    @Override
    public void onPause() {
        super.onPause();
        waveLineView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        waveLineView.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        waveLineView.release();
        mp3Recorder.release();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.bt_start:
                mSinView.startAnim();
                mp3Recorder.startRecord();
                waveLineView.startAnim();
                break;
            case R.id.bt_stop:
                mSinView.stopAnim();
                mp3Recorder.stopRecord();
                waveLineView.stopAnim();
                break;
            case R.id.bt_add_progress:
                progress += 5;
                progressWithTime.setProgress(progress);
                break;
        }
    }
}
